package singsong;

public class AudioClipComparator {

	private final float waveDiffThreshold;
	
	private final int samples;
	
	private final float maxScorePerSample;
	
	public AudioClipComparator(float waveDiffThreshold, int samples) {
		this.waveDiffThreshold = waveDiffThreshold;
		this.samples = samples;
		this.maxScorePerSample = 1.0f / samples;
	}
	
	public boolean compare(AudioClip a, AudioClip b) {
		return computeWaveDiffFrac(a, b) < waveDiffThreshold;
	}

	public float computeWaveDiffFrac(AudioClip a, AudioClip b) {
		float diffFrac = 0;
		for (int i = 0; i < samples; ++i) {
			float frac = ((float) i) / samples;
			float sampleA = a.getSampleAtFrac(frac);
			float sampleB = b.getSampleAtFrac(frac);
			diffFrac += maxScorePerSample * Math.min(1.0, Math.abs(sampleB - sampleA) / 2.0f);
		}
		return diffFrac;
	}
}
